package com.shenganyuan.smac.risk;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.View;
import android.widget.TextView;

import com.amap.api.maps2d.model.LatLng;
import com.oklib.utils.helper.RxUtil;
import com.oklib.utils.network.http.ViseHttp;
import com.oklib.utils.network.http.callback.ACallback;
import com.oklib.utils.network.http.subscriber.ApiCallbackSubscriber;
import com.oklib.utils.network.loader.ILoader;
import com.oklib.utils.network.loader.LoaderManager;
import com.oklib.utils.view.SnackbarUtil;
import com.oklib.widget.recyclerview.BaseQuickAdapter;
import com.oklib.widget.recyclerview.BaseViewHolder;
import com.oklib.widget.recyclerview.CoreRecyclerView;
import com.oklib.widget.recyclerview.listener.OnItemChildClickListener;
import com.oklib.widget.recyclerview.listener.OnItemClickListener;
import com.shenganyuan.smac.App;
import com.shenganyuan.smac.R;
import com.shenganyuan.smac.change.ActChangeInfo;
import com.shenganyuan.smac.change.ActChangeInfoAdd;
import com.shenganyuan.smac.common.BaseActivity;
import com.shenganyuan.smac.common.Config;
import com.shenganyuan.smac.common.beans.ApiRiskPoints;
import com.shenganyuan.smac.common.beans.ApiRiskRecords;
import com.shenganyuan.smac.common.beans.EventRefreshPage;
import com.shenganyuan.smac.common.beans.RiskInfo;
import com.shenganyuan.smac.common.beans.RiskPoint;
import com.shenganyuan.smac.common.beans.User;
import com.shenganyuan.smac.common.data.Api;
import com.shenganyuan.smac.common.utils.DataConverter;
import com.shenganyuan.smac.common.view.CommonBottomListDialog;
import com.shenganyuan.smac.common.view.RecyclerViewItemDivider;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * 隐患记录
 *
 * @author Damon
 */

public class ActRiskRecords extends BaseActivity {
    @BindView(R.id.work_check_record_recycler)
    CoreRecyclerView recycler;
    @BindView(R.id.toolbar)
    Toolbar toolbar;

    @BindView(R.id.txt_check_position)
    TextView txt_check_position;
    @BindView(R.id.container_check_position)
    View container_check_position;
    //巡查位置集合
    List<RiskPoint> points = new ArrayList<>();
    private RiskPoint currentPoint;
    private BaseQuickAdapter baseQuickAdapter;

    @Override
    public int getLayoutId() {
        return R.layout.act_risk_records;
    }

    @Override
    public void initUI(Bundle savedInstanceState) {
        EventBus.getDefault().register(this);
        baseQuickAdapter = new BaseQuickAdapter<RiskInfo, BaseViewHolder>(R.layout.act_risk_record_item) {
            @Override
            protected void convert(BaseViewHolder helper, RiskInfo item) {
                helper.setText(R.id.tv_position, item.getGkZydyName()).addOnClickListener(R.id.tv_position);
                helper.setText(R.id.tv_desc, item.getYhnr());
                helper.setText(R.id.tv_time, DataConverter.getDateStr(item.getLrTime()));
                //整改状态
                if ("N".equalsIgnoreCase(item.getZgzt())) {
                    helper.setImageResource(R.id.to_change, R.drawable.ic_build_black_36dp).addOnClickListener(R.id.to_change);
                    helper.setText(R.id.to_change_txt, "整改").addOnClickListener(R.id.to_change_txt);
                    ((TextView) helper.getView(R.id.to_change_txt)).setTextColor(getResources().getColor(R.color.palevioletred));

                } else {
                    helper.setImageResource(R.id.to_change, R.drawable.ic_build_ok_36dp);
                    helper.setText(R.id.to_change_txt, "已整改");
                    ((TextView) helper.getView(R.id.to_change_txt)).setTextColor(getResources().getColor(R.color.forestgreen));
                }

                String imgStrs = item.getYhzp();
                if (imgStrs != null) {
                    String imgUrl = "";
                    if (imgStrs.contains(";")) {
                        String urls[] = imgStrs.split(";");
                        imgUrl = urls[0];
                    } else {
                        imgUrl = imgStrs;
                    }
                    LoaderManager.getLoader().loadNet(helper.getView(R.id.img), imgUrl, new ILoader.Options(R.drawable.lib_img_default, R.drawable.lib_img_default));
                }
            }
        };
        recycler.init(baseQuickAdapter);
        recycler.getRecyclerView().
                addItemDecoration(new RecyclerViewItemDivider(mContext, LinearLayoutManager.VERTICAL)
                        .setAppearance(20, "#eeeeee"));
        recycler.addOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onSimpleItemClick(BaseQuickAdapter adapter, View view, int position) {
                RiskInfo item = (RiskInfo) adapter.getItem(position);
                if ("Y".equalsIgnoreCase(item.getZgzt())) {
                    gotoDetail(item);
                }
            }
        });
        recycler.addOnChildItemClickListener(new OnItemChildClickListener() {
            @Override
            public void onSimpleItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                RiskInfo item = (RiskInfo) adapter.getItem(position);
                switch (view.getId()) {
                    case R.id.tv_position:
                        String gps = item.getGps();
                        LatLng latLng = DataConverter.fromStrToLatLng(gps);
                        if (latLng == null) {
                            SnackbarUtil.show(getWindow().getDecorView(), "不可用的定位数据");
                            return;
                        }
                        DataConverter.openSdkMap(mContext, latLng.latitude, latLng.longitude);
                        break;
                    case R.id.to_change:
                        if ("N".equalsIgnoreCase(item.getZgzt())) {
                            gotoChange(item, view);
                        }
                        break;
                    case R.id.to_change_txt:
                        if ("N".equalsIgnoreCase(item.getZgzt())) {
                            gotoChange(item, view);
                        }
                        break;
                }
            }
        });
        recycler.openRefresh(new CoreRecyclerView.addDataListener() {
            @Override
            public void addData(int page) {
                getServerData(currentPoint);
            }
        });


    }

    /**
     * 去整改
     *
     * @param item
     * @param view
     */
    private void gotoChange(RiskInfo item, View view) {
        Bundle bundle = new Bundle();
        bundle.putSerializable("pcyhxxid", item.getId());
        bundle.putString("from", "risk");
        Intent intent = new Intent(this, ActChangeInfoAdd.class);
        intent.putExtras(bundle);
        startActivity(intent);
    }

    /**
     * 去详情页
     *
     * @param item
     */
    private void gotoDetail(RiskInfo item) {
        Bundle bundle = new Bundle();
        bundle.putSerializable("pcyhxxid", item.getId());
        Intent intent = new Intent(this, ActChangeInfo.class);
        intent.putExtras(bundle);
        startActivity(intent);
    }

    @Override
    public void initData() {
        setTitle("隐患记录");
        getRiskPointFromServer();
        getServerData(currentPoint);
        txt_check_position.setText("全部");
    }

    /**
     * 获取风险点集合
     */
    private void getRiskPointFromServer() {
        User user = App.getCurrentUser();
        ViseHttp.RETROFIT().create(Api.class).getRiskPoints(user.getId(), App.getAccessToken())
                .compose(RxUtil.rxSchedulerHelper()).subscribe(new ApiCallbackSubscriber<>(new ACallback<ApiRiskPoints>() {
            @Override
            public void onSuccess(ApiRiskPoints data) {
                try {
                    if ("true".equalsIgnoreCase(data.getResult())) {
                        points.clear();
                        points.addAll(data.getGkzydy());
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFail(int errCode, String errMsg) {
                SnackbarUtil.showShort(getWindow().getDecorView(), "获取巡查点信息失败");
            }
        }));
    }

    /**
     * 获取隐患信息
     *
     * @param riskPoint
     */
    private void getServerData(RiskPoint riskPoint) {
        String pointId = null;
        if (riskPoint != null) {
            pointId = riskPoint.getId();
        }
        User user = App.getCurrentUser();
        ViseHttp.RETROFIT().create(Api.class).getRiskRecords(user.getId(), pointId, App.getAccessToken())
                .compose(RxUtil.rxSchedulerHelper()).subscribe(new ApiCallbackSubscriber<>(new ACallback<ApiRiskRecords>() {
            @Override
            public void onSuccess(ApiRiskRecords data) {
                try {
                    if ("true".equalsIgnoreCase(data.getResult())) {
                        recycler.getAdapter().setNewData(data.getPcyhxx());
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFail(int errCode, String errMsg) {
                SnackbarUtil.showShort(getWindow().getDecorView(), "获取隐患记录信息失败");
            }
        }));
    }

    /**
     * 选择巡查点
     */
    public void pickPosition() {
        ArrayList<String> datas = new ArrayList<>();
        for (int i = 0; i < points.size(); i++) {
            if (TextUtils.isEmpty(points.get(i).getId())) {
                datas.add("全部");
            } else {
                datas.add(points.get(i).getName());
            }
        }
        CommonBottomListDialog commonBottomListDialog = CommonBottomListDialog.newInstance(datas);
        commonBottomListDialog.setTitle(getString(R.string.tilte_choose_position));
        commonBottomListDialog.setDefaultCheckValue(txt_check_position.getText().toString());
        commonBottomListDialog.addOnSingleCheckListener(new CommonBottomListDialog.OnSingleCheckListener() {
            @Override
            public void onSingleCheck(int position, String value) {
                txt_check_position.setText(value);
                currentPoint = points.get(position);
                getServerData(currentPoint);
            }
        });
        commonBottomListDialog.show(getSupportFragmentManager(), "check_position");
    }

    @OnClick({R.id.container_check_position})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.container_check_position:
                pickPosition();
                break;
        }
    }

    @Subscribe
    public void onEventRefreshPage(EventRefreshPage iEvent) {
        if (iEvent != null) {
            if (iEvent.type == Config.EventKit.KEY_EVENT_REFRESH_ACTRISKRECORDS) {
                refreshPage();
            }
        }
    }

    @Override
    protected void onResume() {
        super.onResume();

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    /**
     * 刷新页面数据
     */
    private void refreshPage() {
        getServerData(currentPoint);
    }
}
